package net.anzhuo.controller.es;


import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;

import org.apache.commons.lang.time.DateUtils;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.bulk.BulkRequestBuilder;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.support.WriteRequest.RefreshPolicy;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.index.query.Operator;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


import lombok.extern.slf4j.Slf4j;
import net.anzhuo.common.base.BaseController;
import net.anzhuo.common.utils.DateUtil;
import net.anzhuo.common.utils.RandomGUID;
import net.anzhuo.entity.GsBase;
import net.anzhuo.entity.GsPriority;
import net.anzhuo.entity.GsQuery;
import net.anzhuo.entity.es.Paging;
import net.anzhuo.entity.es.Result;
import net.anzhuo.entity.es.SearchResult;
import net.anzhuo.service.GsBaseService;
import net.anzhuo.service.GsPriorityService;
import net.anzhuo.service.GsQueryService;
import net.sf.json.JSONObject;

@RestController
@Slf4j
public class EsUpdateController extends BaseController {

	@Autowired
	private TransportClient client;
	
	
	@Autowired
	private GsBaseService gsBaseService;
	
	
	@Autowired
	private GsQueryService gsQueryService;
	
	

	@RequestMapping("/UpdateBaseEs")
	public net.anzhuo.entity.db.syncdata.Result UpdateBaseEs(String KeyNo) {
		
		long startTime=System.currentTimeMillis();
		net.anzhuo.entity.db.syncdata.Result result=new net.anzhuo.entity.db.syncdata.Result();
		GsBase gsBase=new GsBase();
		gsBase=gsBaseService.getByMd5(KeyNo);
		String docId="";
		boolean isExists=false;
		String pageIndex="1";
		int pageSize=100;
		if(gsBase!=null)
		{
			isExists=true;
			if(gsBase.getCreditCode()!=null)
			{
			QueryBuilder query = QueryBuilders.boolQuery()
					.must(QueryBuilders.boolQuery()
						.must(QueryBuilders.matchPhraseQuery("credit_code",gsBase.getCreditCode() )));
			
			SearchResponse response = client.prepareSearch("gs").setTypes("gs_base").setQuery(query).addSort("weight", SortOrder.DESC).addSort("_score", SortOrder.DESC).setFrom((Integer.parseInt(pageIndex)-1)*pageSize).setSize(pageSize).execute().actionGet();
			if (response.getHits().getTotalHits()>0) {
				{
					for (SearchHit searchHit : response.getHits()) {
						docId=searchHit.getId();
						log.info("docId="+docId+",name="+(String)searchHit.getSource().get("name"));
					}
					}
				}
			}
		}else
		{
			result.setStatus("202");
			result.setMessage("Update es basic info not exists!");
			return result;
		}
		
	
		
			
		if(docId!=null&&!docId.equals(""))
			{
			UpdateRequest updateRequest = new UpdateRequest();
	        updateRequest.index("gs");
	        updateRequest.type("gs_base");
	        updateRequest.id(""+docId);
	        try {
				updateRequest.doc(XContentFactory.jsonBuilder()
				        .startObject()
				        // 对没有的字段添加, 对已有的字段替换
				            .field("name", gsBase.getName())
				            .field("legal",gsBase.getLegal())
				            .field("name2",gsBase.getName2())
				            .field("tel",gsBase.getTel())
				            .field("email",gsBase.getEmail())
				            .field("web_site",gsBase.getWebSite())
				            .field("reg_zb",gsBase.getRegZb())
				            .field("reg_time",gsBase.getRegTime())
				            .field("enterprise_status",gsBase.getEnterpriseStatus())
				            .field("credit_code",gsBase.getCreditCode())
				            .field("enterprise_type",gsBase.getEnterpriseType())
				            .field("reg_address",gsBase.getRegAddress())
				            .field("province",gsBase.getProvince())
				            .field("city",gsBase.getCity())
				            .field("area",gsBase.getArea())
				            .field("md5",gsBase.getMd5())
				            .field("industry",gsBase.getIndustry())
				            .field("oper_scope",gsBase.getOperScope())
				            .field("year",gsBase.getYear())
				            .field("weight",gsBase.getWeight())
				        .endObject()).setRefreshPolicy(RefreshPolicy.IMMEDIATE);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	        UpdateResponse response=null;
			try {
				response = client.update(updateRequest).get();
				// 打印
				result.setStatus("200");
				result.setMessage("Update es doc success!");
		        String index = response.getIndex();
		        String type = response.getType();
		        String id = response.getId();
		        long version = response.getVersion();
		        System.out.println(index + " : " + type + ": " + id + ": " + version);
			} catch (InterruptedException | ExecutionException e) {
				// TODO Auto-generated catch block
				result.setStatus("201");
				result.setMessage("Update es doc fail!");
				e.printStackTrace();
			}
	        
	        
		}else
		{
			
			try {
			 BulkRequestBuilder bulkRequest = client.prepareBulk();
			 bulkRequest.setRefreshPolicy(RefreshPolicy.IMMEDIATE);
				bulkRequest.add(client.prepareIndex("gs", "gs_base").setSource(XContentFactory.jsonBuilder()
			                .startObject()
			                .field("name", gsBase.getName())
				            .field("legal",gsBase.getLegal())
				            .field("name2",gsBase.getName2())
				            .field("tel",gsBase.getTel())
				            .field("email",gsBase.getEmail())
				            .field("web_site",gsBase.getWebSite())
				            .field("reg_zb",gsBase.getRegZb())
				            .field("reg_time",gsBase.getRegTime())
				            .field("enterprise_status",gsBase.getEnterpriseStatus())
				            .field("credit_code",gsBase.getCreditCode())
				            .field("enterprise_type",gsBase.getEnterpriseType())
				            .field("reg_address",gsBase.getRegAddress())
				            .field("province",gsBase.getProvince())
				            .field("city",gsBase.getCity())
				            .field("area",gsBase.getArea())
				            .field("md5",gsBase.getMd5())
				            .field("industry",gsBase.getIndustry())
				            .field("oper_scope",gsBase.getOperScope())
				            .field("year",gsBase.getYear())
				            .field("weight",gsBase.getWeight())
			                .endObject()
			              )
		          );
				
				
			//	BulkResponse bulkResponse = bulkRequest.get();

		        
		      
		        

		        BulkResponse bulkResponse = bulkRequest.execute().actionGet();
		        if (bulkResponse.hasFailures()) {
		            // process failures by iterating through each bulk response item
		            System.out.println(bulkResponse.getItems().toString());
		            result.setStatus("201");
					result.setMessage("Update es doc fail!");
		        }
		        bulkRequest = client.prepareBulk();
		        result.setStatus("200");
				result.setMessage("Add es doc success!");
			}catch(Exception e)
			{
				log.error(" add es error.");
			}
			
		}
		
		
		 long endTime=System.currentTimeMillis();
		 float excTime=(float)(endTime-startTime)/1000;
		 log.info(" update es 执行时间："+excTime+"s");
		return result;
	}
}
